#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <cstring>
#include <strings.h>
#include <cerrno>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

namespace Server
{
    using namespace std;
    static const string defaultIp = "0.0.0.0";
    static const int gnum = 1024;
    enum
    {
        USAGE_ERR = 1,
        SOCKET_ERR,
        BIND_ERR
    };
    class udpServer
    {
    public:
        udpServer(const uint16_t port, const string &ip = defaultIp) : _port(port), _ip(ip), _sockfd(-1)
        {
        }
        void initServer() // 初始化服务器
        {
            _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sockfd == -1)
            {
                cerr << "socket error：" << errno << " : " << strerror(errno) << endl;
                exit(SOCKET_ERR);
            }
            // 这里我们要进行的是网络通信，所以需要绑定端口号和ip地址 网络通信用的结构是sockaddr_in
            struct sockaddr_in local;
            bzero(&local, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            // local.sin_addr.s_addr = inet_addr(_ip.c_str());
            local.sin_addr.s_addr = htonl(INADDR_ANY); // 绑定任意ip，就是随便哪一个IP地址给我这个端口发东西，我都可以接收
            int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
            if (n == -1)
            {
                cerr << "bind error:" << errno << " : " << strerror(errno) << endl;
                exit(BIND_ERR);
            }
        }
        void start() // 运行服务器
        {
            // 服务器的本质就是一个死循环
            char buffer[gnum];
            for (;;)
            {
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                ssize_t s = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
                if (s > 0)
                {
                    buffer[s] = 0;
                    string clientip = inet_ntoa(peer.sin_addr);
                    uint16_t clientport = ntohs(peer.sin_port);
                    string message = buffer;
                    cout << clientip << "[" << clientport << "]" << message << endl;
                }
            }
        }
        ~udpServer()
        {
        }

    private:
        uint16_t _port;
        string _ip;
        int _sockfd;
    };
} // namespace Server
